var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    blankshow: false,
    blanktips: '~购物车空空如也~',
    totalprice: '0.00',
    totalcount: '0',
    canclick: false,
    cartLoaded: false,
    alldealtype: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      alldealtype:''
    });
    app.ready(() => {
      this.loadCarList();
    });
    app.error(err => {
      if (!app.globalData.userWxInfo) {
        wx.navigateTo({
          url: '/pages/auth/auth',
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareToIndex();
  },

  // 加载购物列表
  loadCarList: function () {
    app.showLoading();
    var url = '/index.php/api/Cart/index';
    app.request(url).then(this.carListCallBack.bind(this))
  },
  carListCallBack: function (result) {
    app.hideLoading();
    if(result.status != 'ok'){
      return;
    }
    var carlist = [];
    for (var i = 0; i < result.arr.length; i++) {
      var goodsinfo = {};
      goodsinfo.orderid = result.arr[i].id;
      goodsinfo.goods_id = result.arr[i].goods_id;
      goodsinfo.name = result.arr[i].goods_name;
      goodsinfo.buycount = result.arr[i].goods_num;
      goodsinfo.price = result.arr[i].goods_price;
      goodsinfo.mprice = result.arr[i].member_goods_price;
      goodsinfo.mpriceVal = parseFloat(goodsinfo.mprice);
      goodsinfo.priceVal = parseFloat(goodsinfo.price);
      goodsinfo.icon = app.globalData.webUrl + result.arr[i].goods.original_img;
      var standard = [];
      if (result.arr[i].spec_key_name != '') {
        standard = result.arr[i].spec_key_name.split(' ');
        for (var j = 0; j < standard.length; j++) {
          standard[j] = standard[j].split(':')[1];
        }
      }
      goodsinfo.standard = standard;
      carlist.push(goodsinfo);
    }
    var blankshow = true;
    if (carlist.length > 0) {
      blankshow = false;
    }
    var totalprice = getApp().keepTwoDecimalFull(0);
    this.setData({
      orders: carlist,
      totalprice: totalprice,
      blankshow: blankshow,
      totalcount: 0,
      canclick: true,
      cartLoaded: true
    });
  },
  // 修改购买数量
  changeBuyCount: function (event) {
    if(!this.data.canclick){
      return;
    }
    var status = parseInt(event.currentTarget.dataset.status);
    var orderid = event.currentTarget.dataset.orderitem;
    var orderlist = this.data['orders'];
    var catid = '', buynum = '0';
    for (var i = 0; i < orderlist.length; i++) {
      if (orderlist[i].orderid == orderid) {
        var cur_status = parseInt(orderlist[i].buycount);
        cur_status += status;
        if (cur_status > 999) {
          cur_status = 999;
        }
        else if (cur_status <= 0) {
          cur_status = 1;
        }
        orderlist[i].buycount = cur_status;
        catid = orderid;
        buynum = cur_status;
        break;
      }
    }
    var url = '/index.php/api/Cart/changeNum';
    var params = {
      id: catid,
      goods_num: buynum
    }
    app.request(url, params).then(this.changeNumCallBack.bind(this));
  },
  changeNumCallBack: function (res) {
    if (res.status == 'ok') {
      wx.showToast({
        icon: 'success',
        title: '商品数量修改成功'
      });
      this.loadCarList();
    }
    else {
      wx.showToast({
        icon: 'none',
        title: (res.msg + res.result.limit_num)
      });
    }
  },
  // 输入购买数量
  numInputCheck: function (event) {
    var orderid = event.currentTarget.dataset.orderitem;
    var inputval = event.detail.value;
    var buycount = parseInt(inputval);
    if (buycount > 999) {
      buycount = 999;
    }
    else if (buycount <= 0) {
      buycount = 1;
    }
    var orderlist = this.data['orders'];
    for (var i = 0; i < orderlist.length; i++) {
      if (orderlist[i].orderid == orderid) {
        orderlist[i].buycount = buycount;
        break;
      }
    }
    this.setData({
      orders: orderlist
    });
  },
  // 确认输入
  numInputConfirm: function (event) {
    var orderid = event.currentTarget.dataset.orderitem;
    var inputval = event.detail.value;
    var buycount = parseInt(inputval);
    if (buycount > 999) {
      buycount = 999;
    }
    else if (buycount <= 0) {
      buycount = 1;
    }
    var orderlist = this.data['orders'];
    var needupdate = true;
    var catid = '', buynum = '0';
    for (var i = 0; i < orderlist.length; i++) {
      if (orderlist[i].orderid == orderid) {
        if (orderlist[i].buycount.toString() == buycount.toString()) {
          needupdate = false;
        }
        else {
          catid = orderid;
          buynum = cur_status;
          orderlist[i].buycount = buycount;
        }
        break;
      }
    }
    if (needupdate == false) {
      return;
    }
    var url = '/index.php/api/Cart/changeNum';
    var params = {
      id: catid,
      goods_num: buynum
    }
    app.request(url, params).then(this.changeNumCallBack.bind(this))
  },
  // 选择订单
  chooseOrder: function (event) {
    if (!this.data.canclick) {
      return;
    }
    var orderid = event.currentTarget.dataset.orderitem;
    var totalprice = parseFloat(this.data.totalprice);
    var totalcount = this.data.totalcount;
    var orderlist = this.data['orders'];
    for (var i = 0; i < orderlist.length; i++) {
      if (orderlist[i].orderid == orderid) {
        if (orderlist[i].dealtype == 'success_no_circle') {
          orderlist[i].dealtype = '';
        }
        else {
          orderlist[i].dealtype = 'success_no_circle';
        }
        break;
      }
    }
    this.setData({
      orders: orderlist
    });
    this.check_allChoose();
    this.updateOrderChoose();
  },
  updateOrderChoose: function () {
    var cartStatus_arr = [];
    // var cartStatus_arr = {};
    var orderlist = this.data['orders'];
    for (var i = 0; i < orderlist.length; i++) {
      var cartid = orderlist[i].orderid;
      var selected = orderlist[i].dealtype == 'success_no_circle' ? '1' : '0';
      var cartStatus = {
        id: cartid,
        selected: selected
      };
      cartStatus_arr.push(cartStatus);
    }
    var url = '/index.php/api/Cart/AsyncUpdateCart';
    var params = {
      cart: cartStatus_arr
    };
    app.showLoading();
    app.request(url, params).then(this.updateOrderChooseCallBack.bind(this));
  },
  updateOrderChooseCallBack: function (res) {
    app.hideLoading();
    if (res.status == 'ok' || res.status == 1) {
      var fee = app.keepTwoDecimalFull(res.result.total_fee);
      this.setData({
        totalprice: fee,
        totalcount: res.result.goods_num
      });
    }
  },
  // 检测是否全选
  check_allChoose: function () {
    var all_dealtype = 'success_no_circle';
    var allChhose = true;
    var orderlist = this.data['orders'];
    for (var i = 0; i < orderlist.length; i++) {
      if (orderlist[i].dealtype != 'success_no_circle') {
        allChhose = false;
        break;
      }
    }
    if (allChhose == false) {
      all_dealtype = '';
    }
    this.setData({
      alldealtype: all_dealtype
    });
  },
  // 全选
  chooseAllOrder: function () {
    if (!this.data.canclick) {
      return;
    }
    var alldealtype = this.data['alldealtype'];
    var orderlist = this.data['orders'];
    for (var i = 0; i < orderlist.length; i++) {
      if (alldealtype == 'success_no_circle') {
        orderlist[i].dealtype = '';
      }
      else {
        orderlist[i].dealtype = 'success_no_circle';
      }
    }
    if (alldealtype == 'success_no_circle') {
      alldealtype = '';
    }
    else {
      alldealtype = 'success_no_circle';
    }
    this.setData({
      alldealtype: alldealtype,
      orders: orderlist
    });
    this.updateOrderChoose();
  },
  // 结算
  submitOrder: function () {
    var orders = this.data.orders;
    var selected_orders = [];
    for (var i = 0; i < orders.length; i++) {
      if (orders[i].dealtype == 'success_no_circle') {
        selected_orders.push(orders[i]);
      }
    }
    if (selected_orders.length <= 0) {
      wx.showToast({
        image: '../../imgs/tips.png',
        title: '请选择订单',
      });
      return;
    }

    var url = '/index.php/api/Cart/cart2';
    var params = {
      action: ''
    };
    app.request(url, params).then(this.submitOrderCallBack.bind(this));
  },
  submitOrderCallBack: function (res) {
    if (res.status == 'ok') {
      for (var i = 0; i < res.result.cartList.length; i++) {
        res.result.cartList[i].goods.goods_content = '';
      }
      wx.navigateTo({
        url: '../../orderlist/neworder/neworder?orderinfos=' + JSON.stringify(res.result),
      });
    }
    else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  },
  // 删除订单
  deleteOrder: function () {
    var orders = this.data.orders;
    var selected_catid = [];
    for (var i = 0; i < orders.length; i++) {
      if (orders[i].dealtype == 'success_no_circle') {
        selected_catid.push(orders[i].orderid);
      }
    }
    if (selected_catid.length <= 0) {
      wx.showToast({
        title: '未选择',
        icon: 'none'
      })
      return;
    }
    var url = '/index.php/api/Cart/delete';
    var params = {
      cart_ids: selected_catid.join(',')
    };
    app.request(url,params).then(this.deleteCallBack.bind(this));
  },
  deleteCallBack: function (res) {
    if (res.status == 'ok') {
      wx.showToast({
        title: '删除成功',
      });
      this.loadCarList();
    }
    else {
      wx.showToast({
        icon: 'none',
        title: res.msg,
      });
    }
  }
})